﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Diagnostics;

namespace for7raid.vkConnector
{
    /// <summary>
    /// Interaction logic for LoginWindow.xaml
    /// </summary>
    public partial class LoginWindow : Window
    {
        private string token;
        private LoginWindow()
        {
            this.Visibility = System.Windows.Visibility.Collapsed;
            InitializeComponent();
        }

        public static string Login(int AppId, int Permission)
        {
            var uri = @"http://api.vk.com/oauth/authorize?" +
                      "client_id=" + AppId + "&" +
                      "scope=" + Permission + "&" +
                      "redirect_uri=http://api.vk.com/blank.html&" +
                      "display=page&" +
                      "response_type=token";

            var w = new LoginWindow();
            w.webBrowser.Navigate(uri);
            w.Visibility = Visibility.Collapsed;
            w.ShowDialog();

            return w.token;

        }

       
       
        private void WebBrowser_Navigated(object sender, System.Windows.Forms.WebBrowserNavigatedEventArgs e)
        {
            //http://api.vk.com/blank.html#access_token=d5903e079864efe4d548ee42bcd595c60c5d58ad58ad5f2a00cc4c390b2a995&expires_in=86400&user_id=1764349
            var uri = e.Url.ToString();
            if (uri.Contains("access_token"))
            {
                token = uri.Split('#')[1].Split('&')[0].Split('=')[1];
                this.Close();
            }
            else
                this.Visibility = System.Windows.Visibility.Visible;
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(token))
                throw new InvalidOperationException("Не удалось залогиниться в системе!");
        }
    }
}
